package com.wf.course.service.impl;

import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.utils.page.PageBean;
import com.wf.course.dao.ICourseWeixinMapper;
import com.wf.course.model.course.CourseWeixin;
import com.wf.course.service.ICourseWeixinService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;

@Service
@Transactional(rollbackFor=Exception.class)
public class ICourseWeixinServiceImpl implements ICourseWeixinService{
	
	@Autowired
	private ICourseWeixinMapper mapper;

	@Override
	public void indexInfo(PageBean<CourseWeixin> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean));
	}

	@Override
	public void saveOrUpdateCourseWeixin(CourseWeixin courseWeixin,MultipartFile weixinFile) {
		// TODO Auto-generated method stub
		
		//添加
		if(courseWeixin.getId()==null){
			 
			if (!weixinFile.isEmpty()) {
				String twoDimensionCode = "";
				try {
					twoDimensionCode = OSSUtil.addFile(weixinFile, "wf_course/wx", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				courseWeixin.setTwoDimensionCode(twoDimensionCode);
			}
			this.mapper.saveCourseWeixin(courseWeixin);
		}else{
		 //修改
			

			if (weixinFile.getSize() != 0) {
				CourseWeixin cours = mapper.queryCourseWeixinById(courseWeixin.getId());
				try{
					if(StringUtils.isNotBlank(cours.getTwoDimensionCode())){
						// 删除原来图片
						OSSUtil.delete(cours.getTwoDimensionCode(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				// 上传
				String twoDimensionCode = "";
				try {
					twoDimensionCode = OSSUtil.addFile(weixinFile, "wf_course/wx", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				courseWeixin.setTwoDimensionCode(twoDimensionCode);
			}
			
			
		  this.mapper.updateCourseWeixin(courseWeixin);
			
		}
		
	}

	@Override
	public CourseWeixin queryCourseWeixinById(Integer id) {
		// TODO Auto-generated method stub
		return this.mapper.queryCourseWeixinById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(id);
	}

	
	@Override
	public List<CourseWeixin> queryCourseWeixins(){
		return this.mapper.queryCourseWeixins();
	}

	
}
